package com.libinyn.base.pms.controller.sys;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.libinyn.base.pms.common.annotation.SysLog;
import com.libinyn.base.pms.common.utils.Result;
import com.libinyn.base.pms.common.validator.ValidatorUtils;
import com.libinyn.base.pms.common.validator.group.AddGroup;
import com.libinyn.base.pms.common.validator.group.UpdateGroup;
import com.libinyn.base.pms.controller.AbstractController;
import com.libinyn.base.pms.entity.sys.SysUserEntity;
import com.libinyn.base.pms.serivce.sys.SysUserRoleService;
import com.libinyn.base.pms.serivce.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;


/**
 * 系统用户
 * @fileName: SysUserController.java
 * @author: bin.li01
 * @date: 2017/12/10 16:20 
 * @version: v1.0.0
 */
@Api(tags = "系统用户管理")
@Controller
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysUserRoleService sysUserRoleService;

	/**
	 * 查询用户列表
	 */
	@ApiOperation(value = "获取用户列表信息", notes = "分页获取用户列表信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sysUserEntity", value = "用户实体", required = true, dataType = "SysUserEntity"),
			@ApiImplicitParam(name = "pageInfo", value = "分页参数", required = true, dataType = "PageInfo<SysUserEntity>")
	})
	@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
//	@RequiresPermissions("sys:user:list")
	@ResponseBody
	public Result list(SysUserEntity sysUserEntity,PageInfo<SysUserEntity> pageInfo){
		//如果不是超级管理员，则只查询自己创建的角色列表
		List<SysUserEntity> userEntities;
		if (StringUtils.isBlank(sysUserEntity.getUsername())){
			sysUserEntity.setUsername(null);
		}
		try {
			PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
			userEntities = sysUserService.select(sysUserEntity);
			pageInfo = new PageInfo<SysUserEntity>(userEntities);

		} catch (Exception e) {
			logger.error("查询数据失败！",e);
			return Result.error("查询数据失败！");
		}

		return Result.ok().put("page", pageInfo);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@ApiOperation(value = "获取当前登录用户信息", notes = "获取当前登录用户信息")
	@RequestMapping(value = "/info",method = RequestMethod.GET)
	@ResponseBody
	public Result info(){
		return Result.ok().put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@ApiOperation(value = "修改用户密码", notes = "修改用户登录密码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "password", value = "旧密码", required = true, dataType = "String"),
			@ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String")
	})
	@RequestMapping(value = "/password",method = RequestMethod.POST)
	@ResponseBody
	public Result password(String password, String newPassword){

		if (StringUtils.isBlank(password)
				|| StringUtils.isBlank(newPassword)){
			return Result.error("密码不能为空");
		}

		//sha256加密
		password = new Sha256Hash(password).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword).toHex();
		//更新密码
		int count = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(count == 0){
			return Result.error("原密码不正确");
		}
		
		return Result.ok();
	}
	
	/**
	 * 用户信息
	 */
	@ApiOperation(value = "查看用户信息", notes = "根据用户ID查看用户信息")
	@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long",paramType = "path")
	@RequestMapping(value = "/info/{userId}",method = RequestMethod.GET)
//	@RequiresPermissions("sys:user:info")
	@ResponseBody
	public Result info(@PathVariable("userId") Long userId){
		SysUserEntity user;
		try {
			user = sysUserService.selectByPrimaryKey(userId);


		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		} catch (Exception e) {
			logger.error("查询用户失败",e);
			return Result.error("查询用户失败");
		}
		return Result.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@ApiOperation(value = "新增用户", notes = "保存用户信息")
	@ApiImplicitParam(name = "user", value = "用户", required = true, dataType = "SysUserEntity")
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	@SysLog("保存用户")
//	@RequiresPermissions("sys:user:save")
	@ResponseBody
	public Result save(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);

		user.setUpdateBy(getUserId());
		user.setCreateBy(getUserId());
		try {

			sysUserService.insertSelective(user);
		} catch (Exception e) {
			logger.error("新增用户异常",e);
			return Result.error("新增用户异常");
		}

		return Result.ok();
	}
	
	/**
	 * 修改用户
	 */
	@ApiOperation(value = "修改用户", notes = "修改用户信息")
	@ApiImplicitParam(name = "user", value = "用户", required = true, dataType = "SysUserEntity")
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	@SysLog("修改用户")
//	@RequiresPermissions("sys:user:update")
	@ResponseBody
	public Result update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		
		sysUserService.updateUser(user);
		
		return Result.ok();
	}
	
	/**
	 * 删除用户
	 */
	@ApiOperation(value = "删除用户", notes = "删除用户")
	@ApiImplicitParam(name = "userIds", value = "用户ID", required = true, dataType = "Array")
	@RequestMapping(value = "/delete",method = {RequestMethod.GET,RequestMethod.POST})
	@SysLog("删除用户")
//	@RequiresPermissions("sys:user:delete")
	@ResponseBody
	public Result delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return Result.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return Result.error("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return Result.ok();
	}
}
